package com.uw.uwrpc.core.traffic;

import com.uw.uwrpc.core.api.RpcRequest;
import com.uw.uwrpc.core.api.TrafficControl;
import com.uw.uwrpc.core.config.UWRpcProperty;
import com.uw.uwrpc.core.util.SlidingTimeWindow;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class TimeWindowTrafficControl implements TrafficControl {

    private final UWRpcProperty uwRpcProperty;
    private final Map<String, SlidingTimeWindow> windowMap = new HashMap<>();

    public TimeWindowTrafficControl(UWRpcProperty uwRpcProperty) {
        this.uwRpcProperty = uwRpcProperty;
    }

    @Override
    public boolean allow(RpcRequest rpcRequest) {
        synchronized (windowMap) {
            SlidingTimeWindow window = windowMap.computeIfAbsent(rpcRequest.requestSign(), k -> new SlidingTimeWindow());
            window.record(System.currentTimeMillis());
            Integer tpsLimit = uwRpcProperty.getProvider().getTpsLimit();
            if (window.calcSum() >= tpsLimit) {
                return false;
            } else {
                log.debug("requestSign {} in window with sum:{}, tpsLimit:{}", rpcRequest.requestSign(), window.getSum(), tpsLimit);
                return true;
            }
        }
    }
}
